import AxiosDigestAuth from "@mhoc/axios-digest-auth";
import log from "./logger";
// import settings from "./settings";
// import {send} from "./metric";
import config from "./config";
import {sendMqtt} from "./mqtt_publish"

const timeoutDuration = 60 * 1000 * 5; // 设置超时时间为1分钟（60,000毫秒）

interface Camera {
    ip: string;
    username: string;
    password: string;
    name: string;
    location: string;
}


interface LastDataTimestamps {
    [cameraUrl: string]: number;
}

// 存储每个摄像头最后接收数据的时间戳
let lastDataTimestamps: LastDataTimestamps = {};


class TemperatureWorker {
    // 摄像头信息数组
    cameras: Camera[] = []

    init() {
        for (let value of config.list) {
            this.cameras.push({
                ip: value.ip,
                username: value.username,
                password: value.password,
                name: value.name,
                location: value.location
            })
        }

        // 初始化每个摄像头的请求和时间戳
        this.cameras.forEach(camera => {
            lastDataTimestamps[camera.ip] = Date.now();
            this.requestData(camera);
        });

        // 循环检查是否超时
        setInterval(() => {
            const now = Date.now();
            this.cameras.forEach(camera => {
                if (now - lastDataTimestamps[camera.ip] > timeoutDuration) {
                    // 如果超过了指定时间没有接收到数据，则重新请求
                    log.info(`Data timeout for camera at ${camera.ip}, sending a new request.`);
                    this.requestData(camera);
                    lastDataTimestamps[camera.ip] = now; // 重置时间戳
                }
            });
        }, timeoutDuration);
    }

    requestData(camera: Camera) {
        // const cameraName = camera.name;
        log.info("开启请求", camera.name)
        let counter = 0;
        const digestAuth = new AxiosDigestAuth({
            username: camera.username,
            password: camera.password,
        });
        digestAuth.request({
            responseType: 'stream',
            method: 'GET',
            url: `http://${camera.ip}/ISAPI/Thermal/channels/2/thermometry/realTimethermometry/rules?format=json`
        }).then(response => {
            response.data.on('data', (chunk: any) => {
                // log.info(`${camera.ip},chunk.toString(): ${chunk.toString()}`);
                // 更新最后接收数据的时间戳
                lastDataTimestamps[camera.ip] = Date.now();
                if (chunk.toString().trim().startsWith("{")) {
                    if (counter > 30) {
                        log.info(`${camera.name},${camera.ip},counter>30`)
                        let obj = JSON.parse(chunk.toString());
                        let linePolygonThermCfg = obj.ThermometryUploadList.ThermometryUpload[0].LinePolygonThermCfg;
                        counter = 0
                        // send("coal", {
                        //     name: config.name,
                        //     platformName: config.platformName,
                        //     platformId: config.platformId,
                        //     cameraName: camera.name
                        // }, "temperature", linePolygonThermCfg.MaxTemperature);
                        sendMqtt(camera.name, camera.location, linePolygonThermCfg.MaxTemperature)
                    }
                    counter++;
                }
            });
            response.data.on('end', () => {
                log.info("end")
            });
            response.data.on('error', () => {
                log.info("error")
            });
            response.data.on('close', () => {
                log.info("close")
            });
        }).catch((e)=>{
            log.error("请求错误", camera.name)
        })
    }
}

const temperatureWorker = new TemperatureWorker();
export default temperatureWorker;